package com.edu.project.utils;

import android.util.Base64;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密处理类
 * Created by ming on 15/11/17.
 */
public class CryptoUtils {
    public static final String DEFAULT_CODING = "utf-8";

    // 密钥
    private static String key = "ess)@a1;`fwer!@#";

   //Aes加密
    public static String AesEncrypt(String content) throws Exception {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
            content = content + "|" + sdf.format(new Date());

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(key.getBytes("utf-8"), "AES"));

            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //Aes解密
    public static String AesDecrypt(String content)  {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,
                    new SecretKeySpec(key.getBytes("utf-8"), "AES"));

            byte[] rawContent = Base64.decode(content.getBytes(DEFAULT_CODING), Base64.DEFAULT);
            byte[] encrypted = cipher.doFinal(rawContent);

            String result = new String(encrypted);
            String[] split = result.split("\\|");

            return split[0];

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
